#include "RegExp.h"
#include "Tracer.h"
#include <stdlib.h>
#include <regex.h>

RegExp::RegExp()
{
}

RegExp::~RegExp()
{
}

bool RegExp::match(const std::string& pattern,const std::string& source,std::string& result)
{
    StringArray strArray;
    IntArray posArray;
    result.clear();
    bool ret = match(pattern,source,strArray,posArray,1);
    if (ret)
    {
        result = strArray[0];
    }
    return ret;
}

bool RegExp::match(const std::string& pattern, const std::string& source,StringArray & strArray, IntArray & posArray,int maxMatches)
{
    regex_t regex;
    if (0!=regcomp(&regex,pattern.c_str(),REG_EXTENDED))
    {
        TRACE_ERR_CLASS("regex compile error!\n");
        return false;
    }
    strArray.clear();
    posArray.clear();
    char* pStr = (char*)source.c_str();
    char* pStart = pStr;
    for(int i=0; i<maxMatches; i++)
    {
        regmatch_t regmatch;
        if (0!=regexec(&regex,pStr,1,&regmatch,0))
        {
            TRACE_ERR_CLASS("regex execute error!\n");
            break;
        }
        else
        {
            if (regmatch.rm_so!=-1)
            {
                std::string result=std::string(pStr).substr(regmatch.rm_so,regmatch.rm_eo-regmatch.rm_so);
                posArray<<(int)(pStr+regmatch.rm_so-pStart);
                strArray<<result;
                pStr = pStr+regmatch.rm_eo;
            }
            else
            {
                break;
            }
        }
    }
    regfree(&regex);
    return true;
}